<?php

namespace App\Imports;


use App\Models\ExhibitorInformation;
use Encore\Admin\Actions\Action;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Hash;
use Maatwebsite\Excel\Facades\Excel;
use Encore\Admin\Admin;


class CertifImports extends Action
{
    //必须的导入按钮样式
    protected $selector = '.import-action';
    protected $messages = '';
    protected $data_excel = [];

    /**
     * @param Request $request
     * @return $this
     */
    public function handle(Request $request)
    {
        try {
            $file = $request->file('file');
            if (!$file) {
                return $this->response()->error('上传文件为空');
            }
            $aAllowExtension = ['xls', 'xlsx'];
            $sFileExtension = $file->getClientOriginalExtension();
            if (!in_array($sFileExtension, $aAllowExtension)) {
                return $this->response()->error('您上传的文件后缀不支持，支持' . implode(',', $aAllowExtension));
            }
            //判断大小是否符合20M
            if ($file->getClientSize() >= 20480000) {
                return $this->response()->error('您上传的的文件过大，最大20M');
            }

            $msg = '';
            $data = Excel::toArray($request, $file);
            $insert_data = [];
            if (!empty($data)) {
                $arr = $data[0];
                unset($arr[0]);

                $type_array = __('certificates.type_array');
                foreach ($arr as $rows) {
                    $exhibitor_information_name = $rows[0];
                    $exhibitor_information = ExhibitorInformation::query()->where('name', $exhibitor_information_name)->first();
                    if ($exhibitor_information) {
                        $exhibitor_information_id=$exhibitor_information->id;
                        $key = array_search($rows[2], $type_array);

                        $type_id = 1;
                        if ($key !== false) {
                            // 使用 unset 删除该元素
                            $type_id = $key;
                        }
                        $insert = [
                            'name' => $rows[1],
                            'type_id' => $type_id,
                            'code' => $rows[3],
                            'phone' => $rows[4],
                            'e_mail' => $rows[5],
                            'exhibitor_information_id' => $exhibitor_information_id,
                        ];
                        $insert_data[] = $insert;
                    } else {
                        $msg = "{$exhibitor_information_name}不存在";
                        break;
                    }


                }
                if ($insert_data) {
                    DB::table('certificates')->insert($insert_data);
                }

            }
            if ($msg) {
                return $this->response()->error('导入错误' . $msg)->refresh();
            } else {
                return $this->response()->warning('导入成功' . count($insert_data) . '<br>' . $this->messages)->refresh();
            }


        } catch (\Exception $e) {

            return $this->response()->error($e->getMessage());
        }
    }

    public function html()
    {

        return <<<HTML
        <a class="btn btn-sm btn-default import-action">导入</a>
        <a class="btn btn-sm btn-default import-action" href="/展商证件申请.xlsx"  target="_blank" >模板下载</a>

HTML;
    }

    /**
     * 表单
     */
    public function form()
    {
        $this->file('file', '请选择文件');
    }

    /**
     * 上传等待
     * @return string
     */
    public function handleActionPromise()
    {
        $resolve = <<<SCRIPT
var actionResolverss = function (data) {
            $('.modal-footer').show()
            $('.tips').remove()
            var response = data[0];
            var target   = data[1];

            if (typeof response !== 'object') {
                return $.admin.swal({type: 'error', title: 'Oops!'});
            }

            var then = function (then) {
                if (then.action == 'refresh') {
                    $.admin.reload();
                }

                if (then.action == 'download') {
                    window.open(then.value, '_blank');
                }

                if (then.action == 'redirect') {
                    $.admin.redirect(then.value);
                }
            };

            if (typeof response.html === 'string') {
                target.html(response.html);
            }

            if (typeof response.swal === 'object') {
                $.admin.swal(response.swal);
            }

            if (typeof response.toastr === 'object') {
                $.admin.toastr[response.toastr.type](response.toastr.content, '', response.toastr.options);
            }

            if (response.then) {
              then(response.then);
            }
        };

        var actionCatcherss = function (request) {
            $('.modal-footer').show()
            $('.tips').remove()

            if (request && typeof request.responseJSON === 'object') {
                $.admin.toastr.error(request.responseJSON.message, '', {positionClass:"toast-bottom-center", timeOut: 10000}).css("width","500px")
            }
        };
SCRIPT;

        Admin::script($resolve);

        return <<<SCRIPT
         $('.modal-footer').hide()
         <!--let html = `<div class='tips' style='color: red;font-size: 18px;'>导入时间取决于数据量，请耐心等待结果不要关闭窗口！<img src=""><\/div>`-->
         <!--$('.modal-header').append(html)-->
process.then(actionResolverss).catch(actionCatcherss);
SCRIPT;
    }
}
